package com.pusilkom.logger;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileLoger {
	//private FileOutputStream logFOS;	
	private FileOutputStream errFOS;   
    private PrintStream errPS;
    private String logPath;    
    private String processorId;
    private DateFormat dateFormat;
    private DateFormat logTimeFormat;
    private String currentDate;
    
    /**
     * BatchUploadLogger Constructor
     * @param pId
     * @param path
     */
    public FileLoger(String pId, String path) {
    	this.logPath = path;
    	this.processorId = pId;
    	
    	dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        logTimeFormat = new SimpleDateFormat("HH:mm:ss.SSS");
        Date date = new Date();
        currentDate = dateFormat.format(date);
        
        try {        		
			//log error 
			errFOS = new FileOutputStream(logPath + "err-" + processorId + "-" + currentDate + ".txt", true);
			errPS = new PrintStream(errFOS);
		} catch (FileNotFoundException e) {			
			e.printStackTrace();
		}        
    }    
    
    
    /**
     * Write log error batch upload transaction
     * @param errStr
     */
    public void writeException(Exception ex, String errStr) {
    	DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    	Date date = new Date();
    	String strDate = dateFormat.format(date);
    	if (!currentDate.equalsIgnoreCase(strDate)) {
	        try {
				errFOS.close();
				errPS.close();
				
				errFOS = new FileOutputStream(logPath + "log-" + processorId + "-" + currentDate + ".txt", true);
	            errPS = new PrintStream(errFOS);
			} catch (IOException e) {			
				e.printStackTrace();
			}
        }
        date = new Date();
        errPS.println(logTimeFormat.format(date) + ":" + errStr);
        ex.printStackTrace(errPS);
    }
    
}
